package com.five.system.service.impl;

import com.five.basic.service.impl.BaseServiceImpl;
import com.five.dto.RoleDto;
import com.five.pojo.Role;
import com.five.system.mapper.RoleMapper;
import com.five.system.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Transactional
    @Override
    public void delete(Long id) {
        roleMapper.deleteRoleMenus(id);
        roleMapper.deleteRolePermissions(id);
        roleMapper.deleteRoleUsers(id);
        roleMapper.delete(id);
    }

    @Transactional
    @Override
    public void deleteBatch(List<Long> ids) {
        roleMapper.deleteBatchRoleMenus(ids);
        roleMapper.deleteBatchRolePermissions(ids);
        roleMapper.deleteBatchRoleUsers(ids);
        roleMapper.deleteBatch(ids);
    }

    @Transactional
    @Override
    public void updateRole(RoleDto roleDto) {
        Long id = roleDto.getId();
        List<Long> menus = roleDto.getMenus();
        List<Long> permissions = roleDto.getPermissions();
        // 先删除关联表
        roleMapper.deleteRoleMenus(id);
        roleMapper.deleteRolePermissions(id);
        Role role = new Role();
        BeanUtils.copyProperties(roleDto, role);
        roleMapper.update(role);
        // 再添加关联表
        // 2.role_menu
        roleMapper.addRoleMenus(role.getId(), menus);
        // 3.role_permission
        roleMapper.addRolePermissions(role.getId(), permissions);
    }

    @Transactional
    @Override
    public void addRole(RoleDto roleDto) {

        List<Long> menus = roleDto.getMenus();
        List<Long> permissions = roleDto.getPermissions();
        Role role = new Role();
        BeanUtils.copyProperties(roleDto, role);
        roleMapper.add(role);
        // 2.role_menu
        roleMapper.addRoleMenus(role.getId(), menus);
        // 3.role_permission
        roleMapper.addRolePermissions(role.getId(), permissions);


    }
}
